<template>
  <custom-dialog
    ref="dialog" title="绑定角色" width="600px"
    :before-confirm="beforeConfirm" :on-confirm="onConfirm"
  >
    <el-form ref="form" :model="info" :rules="rules" label-width="120px">
      <el-form-item label="选择角色" prop="roleId">
        <el-radio-group v-model="info.roleId">
          <el-radio class="radio-item" v-for="option in roleOption" :label="option.id" :key="option.id">
            {{ option.roleName }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
  </custom-dialog>
</template>

<script>
import CustomDialog from '@/components/custom-dialog'
import { queryList } from '@/api/sysRole'
import { batchByRoleUser } from '@/api/sysRoleUser'

const api = {
  queryList,
  batchByRoleUser
}
export default {
  name: 'select-role-modal',
  props: {
    userIds: {
      type: Array,
      required: true
    },
    modalData: {
      type: Object,
      default () {
        return {}
      }
    },
  },
  components: { CustomDialog },
  data () {
    return {
      info: {
        roleId: ''
      },
      rules: {
        roleId: [{ required: true, message: '请选择角色' }]
      },
      roleOption: []
    }
  },
  methods: {
    getRoleOptions () {
      return api.queryList().then(res => {
        if (res.code === 200) {
          this.roleOption = res.data
        }
      })
    },
    open () {
      this.info = {
        ...this.$options.data().info,
        ...this.modalData,
      }
      if (this.$refs.form) {
        this.$refs.form.resetFields()
      }
      this.getRoleOptions()
      this.$nextTick(() => {
        this.$refs.dialog.open()
      })
    },
    beforeConfirm () {
      return this.$refs.form.validate()
    },
    onConfirm (close) {
      const params = this.userIds.map((v) => ({
        userId: v,
        roleId: this.info.roleId
      }))

      return api.batchByRoleUser(params).then((res) => {
        if (res.code === 200) {
          this.$message.success('绑定成功')
          this.$emit('save-success')
          close()
        }
      })
    }
  }
}
</script>

<style scoped>
  .radio-item {
    display: block;
    padding-top: 10px;
    padding-bottom: 10px;
  }
</style>
